package orderOpe;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import db.DBManager;


public class OpLoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		perform(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		perform(req,resp);
	}
	private void perform(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		req.setCharacterEncoding("UTF-8");
		StringBuffer msg = new StringBuffer();		//エラー用
		
		
		String id = req.getParameter("code");//id受け取り
		String pass = req.getParameter("pass");//パスワード受け取り
		
		//入力チェック
		if(id == null || id.length() == 0)
		{
			msg.append("IDが未入力です。");
		}
		if(pass == null || pass.length() == 0)
		{
			msg.append("パスワードが未入力です。");
		}
		
		String url = "/operator/index.jsp";
		
		//担当者ＩＤ、ＰＡＳＳＷＯＲＤ照会
		Connection con = DBManager.getConnection();
		
		try{
			HttpSession session = req.getSession();
			session.removeAttribute("user");
			session.removeAttribute("rights");
			
			String user = "select * from operator where id = " + id;
			Statement stm = con.createStatement();
			ResultSet rs = stm.executeQuery(user);
			if(rs.next()){
				if(id == null || id.length() == 0)
				{
					msg.append("IDが間違っています。\n");
				}
				else if(!pass.equals(rs.getString("pass")))
				{
					msg.append("パスワードが間違っています。");
				}
				else		//エラーがなにもない場合
				{
					session.setAttribute("name", rs.getString("name"));
					session.setAttribute("rights", rs.getInt("rights"));
					url = "/operator/menu.jsp";
				}
			}
			
			rs.close();
			stm.close();
			con.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		
		//エラーが1つでもあればエラー情報をもって戻る
		req.setAttribute("msg", msg.toString());
		req.setAttribute("id", id);
		req.setAttribute("pass", pass);
		RequestDispatcher dispatcher = req.getRequestDispatcher(url);
		dispatcher.forward(req, resp);
	}

}